package com.chapter.sample.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName());
            return 1024;
        });
        new Thread(futureTask, "t1").start();
        //阻塞等待
        System.out.println(futureTask.get());
        //超时机制，等待
        System.out.println(futureTask.get(1, TimeUnit.SECONDS));
        //CAS自旋（轮询代替阻塞）
        while (true) {
            if (futureTask.isDone()) {//询问是否完成
                System.out.println("--result-- : " + futureTask.get());
                break;
            } else {
                System.out.println("计算中");
            }
        }
    }
}
